package com.jcip.examples;

import static org.junit.Assert.assertTrue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;

public abstract class ConcurrentHardness {
	
	protected ExecutorService executor;
	protected static final int CYCLES = 1000000;
	
	@Before
	public void initExecutor() {
		executor = new ThreadPoolExecutor(4, 4, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(CYCLES));
	}

	@After
	public void collectResults() throws InterruptedException {
		waitAllTasks();
		checkResults();
	}

	private void waitAllTasks() throws InterruptedException {
		executor.shutdown();
		boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS);
		assertTrue("Finished all tasks",terminated);
	}
	
	abstract protected void checkResults();
	abstract protected Runnable newTask();

}